package com.scpii.universal.util;

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.scpii.universal.exception.DownloadException;
import com.scpii.universal.io.FileUtil;

/**
 * 文件下载工具类
 * @author yue
 *
 */
public class DownloadFileUtil {

	/**
	 * 文件下载工具，将source文件下载到destinationFolder文件夹！</br> 
	 * destinationFileName如果这个参数为null，则使用原来本身的文件名，否则使用destinationFileName这个文件名
	 * 
	 * @param source
	 *            源文件 一个指向文件的URL地址
	 * @param destinationFolder
	 *            生成的文件存放的文件夹
	 * @param destinationFileName
	 *            新文件的文件名
	 * @return
	 * @throws Exception
	 */
	public static boolean downloadFile(String source, String destinationFolder,String destinationFileName) throws Exception{
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(source);
		HttpResponse response = null;
		try{
			response = client.execute(get);
		}catch(Exception e){
			throw new DownloadException("下载证书时，请求URL资源出错，URL：" + source);
		}
		byte[] resData;
		if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				if (destinationFileName == null){
					destinationFileName = source.substring(source.lastIndexOf("/") + 1);
				}
				String filePath = destinationFolder + File.separator
						+ destinationFileName;
				resData = EntityUtils.toByteArray(entity);
				FileUtil.savefile(filePath, resData, null, null);
			}
		}
		return true;
	}
}
